package com.ouran.webservice.client;

import javax.xml.namespace.QName;

import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.service.model.BindingInfo;
import org.apache.cxf.service.model.BindingOperationInfo;

/**
 * 基于cxf 3.2.5 调用webservice服务
 * @author lijiajun
 * @version 1.0
 * Date 2018/07/28
 */
public class CxfClient {
 
	public static void main(String[] args) throws Exception {
		String url = "http://127.0.0.1:8080/coin/webService/service_endpoint?wsdl";
		String method = "getUserByName";
		com.ouran.webservice.server.User user = new com.ouran.webservice.server.User();
		user.setId(1);
		user.setPassWord("2");
		user.setUserName("李佳君");
		user = (com.ouran.webservice.server.User) invokeRemoteMethod(url, method, user)[0];
		System.out.println("响应的数据为: "+user.toString());
    }
	
	public static Object[] invokeRemoteMethod(String url, String operation, Object parameters){
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        if (!url.endsWith("wsdl")) {
            url += "?wsdl";
        }
        org.apache.cxf.endpoint.Client client = dcf.createClient(url);
        Endpoint endpoint = client.getEndpoint();
        QName opName = new QName(endpoint.getService().getName().getNamespaceURI(),operation);
        BindingInfo bindingInfo= endpoint.getEndpointInfo().getBinding();
        if(bindingInfo.getOperation(opName) == null){
        	for(BindingOperationInfo operationInfo : bindingInfo.getOperations()){
        		if(operation.equals(operationInfo.getName().getLocalPart())){
        			opName = operationInfo.getName();
        			break;
        		}
        	}
        }
		Object[] res = null;
		try {
			res = client.invoke(opName, parameters);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
    } 	
}
